package com.longer.playhelper.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.longer.playhelper.R;
import com.longer.playhelper.adapter.Image_9Adapter;
import com.longer.playhelper.utlis.Toast;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageLoader;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HelpAddfw_Activity extends AppCompatActivity {

    public Context context;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.recy_addpic)
    RecyclerView recycler;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_type)
    TextView tvType;
    @Bind(R.id.tv_addpic_jd)
    TextView tvAddpicJd;
    @Bind(R.id.progress_addpic_progressBar)
    ProgressBar progressAddpicProgressBar;
    @Bind(R.id.iv_type)
    ImageView ivType;


    private Image_9Adapter imagecrtnewsAdapter;
    private ArrayList<String> path = new ArrayList<>();
    private ArrayList<String> uppath = new ArrayList<>();
    //    private static String pic_path = null;//允许用户选择一张图片，所以只保存一个图片地址
    private int num;
    public static final int REQUEST_CODE = 1000;
    private boolean upload = false;//判断是否正在上传中 true是正在上传

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_fw);
        ButterKnife.bind(this);

        toolbar.setTitle("发布服务");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });
        inti();
    }

    public void inti() {
        context = HelpAddfw_Activity.this;
    }


    @OnClick({R.id.tv_addpic, R.id.tv_rzxy, R.id.btn_submit, R.id.card_location, R.id.card_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.card_location:
                startActivityForResult(new Intent(context, CheckLocation_Activity.class), 0);
                break;
            case R.id.tv_addpic:
                // 先判断是否有权限。
                if (AndPermission.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    // 有权限，直接do anything.
                    checkpic();
                } else {
                    //Log.d("tip","没有权限");
                    // 申请权限。
                    AndPermission.with(HelpAddfw_Activity.this)
                            .requestCode(100)
                            .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                            .send();
                }
                break;
            case R.id.tv_rzxy:
                Intent intent = new Intent(context, WebView_Activity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", "file:///android_asset/fuwuxieyi.html");
                startActivity(intent);
                break;
            case R.id.btn_submit:
                Toast.show("功能建设中...");
                break;
            case R.id.card_type:
                showPopupMenu(ivType);
                break;
        }
    }

    private void showPopupMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_help_qz, popupMenu.getMenu());
        // menu的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                tvType.setText(item.getTitle());
                tvType.setTextColor(getResources().getColor(R.color.textview_ok));
                return false;
            }
        });
        popupMenu.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 只需要调用这一句，其它的交给AndPermission吧，最后一个参数是PermissionListener。
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                checkpic();
            } else if (requestCode == 101) {
                Log.d("tip", "100");
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            Toast.show("额，没有权限将无法选择图片！");
        }
    };

    /**
     * 选择照片
     */
    public void checkpic() {
        ImageConfig imageConfig
                = new ImageConfig.Builder(
                // GlideLoader 可用自己用的缓存库
                new GlideLoader())
                // 如果在 4.4 以上，则修改状态栏颜色 （默认黑色）
//                .steepToolBarColor(Color.parseColor(FileTools.getshareString("refreshcolor")))
                // 标题的背景颜色 （默认黑色）
//                .titleBgColor(Color.parseColor(FileTools.getshareString("refreshcolor")))
                // 提交按钮字体的颜色  （默认白色）
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启多选   （默认为多选）  (单选 为 singleSelect)
                .crop()
                // 多选时的最大数量   （默认 9 张）
                .mutiSelectMaxSize(3)
                // 已选择的图片路径
                .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture）
                .filePath("/ImageSelector/Pictures")
                // 开启拍照功能 （默认开启）
                .showCamera()
                .requestCode(REQUEST_CODE)
                .build();
        ImageSelector.open((Activity) context, imageConfig);   // 开启图片选择器
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
        recycler.setLayoutManager(gridLayoutManager);
        imagecrtnewsAdapter = new Image_9Adapter(context, path);
        recycler.setAdapter(imagecrtnewsAdapter);
    }

    public class GlideLoader implements ImageLoader {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context)
                    .load(path)
                    .placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
                    .centerCrop()
                    .into(imageView);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            tvLocation.setText(data.getStringExtra("info"));
            tvLocation.setTextColor(getResources().getColor(R.color.textview_ok));
        }
        if (requestCode == REQUEST_CODE && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            for (String path : pathList) {
                Log.i("ImagePathList", path);
            }
            path.clear();
            path.addAll(pathList);
//            pic_path = pathList.get(pathList.size() - 1);
//            path.add(pic_path);
            imagecrtnewsAdapter.notifyDataSetChanged();
        }
    }
}
